<template>
  <div class="vehicle-management">
    <!-- 车辆列表 -->
    <div class="vehicles-grid">
      <div
        v-for="vehicle in vehicles"
        :key="vehicle.id"
        class="vehicle-card"
        :class="{ inactive: !vehicle.is_active }"
      >
        <div class="vehicle-header">
          <div class="vehicle-info">
            <h3 class="vehicle-name">{{ vehicle.name }}</h3>
            <p class="vehicle-model">{{ vehicle.brand }} {{ vehicle.model }}</p>
            <div class="vehicle-badges">
              <span class="license-plate">{{ vehicle.license_plate }}</span>
              <span v-if="vehicle.year" class="year-badge">
                {{ vehicle.year }}年
              </span>
              <span
                :class="[
                  'status-badge',
                  vehicle.is_active ? 'active' : 'inactive',
                ]"
              >
                {{ vehicle.is_active ? "使用中" : "已停用" }}
              </span>
            </div>
          </div>
          <div class="vehicle-actions">
            <button
              @click="editVehicle(vehicle)"
              class="action-button edit"
              title="编辑"
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              >
                <path
                  d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"
                />
                <path
                  d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"
                />
              </svg>
            </button>
            <button
              @click="deleteVehicle(vehicle)"
              class="action-button delete"
              title="删除"
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              >
                <path
                  d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m3 0v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6h14zM10 11v6M14 11v6"
                />
              </svg>
            </button>
          </div>
        </div>

        <div class="vehicle-details">
          <div class="detail-item">
            <span class="detail-label">创建时间:</span>
            <span class="detail-value">{{
              formatDate(vehicle.created_at)
            }}</span>
          </div>
          <div v-if="vehicle.notes" class="detail-item">
            <span class="detail-label">备注:</span>
            <span class="detail-value">{{ vehicle.notes }}</span>
          </div>
        </div>
      </div>

      <!-- 添加车辆卡片 -->
      <div class="vehicle-card add-vehicle-card" @click="showAddModal = true">
        <div class="add-vehicle-content">
          <svg
            width="48"
            height="48"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
          >
            <line x1="12" y1="5" x2="12" y2="19"></line>
            <line x1="5" y1="12" x2="19" y2="12"></line>
          </svg>
          <span class="add-vehicle-text">添加车辆</span>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="vehicles.length === 0 && !loading" class="empty-state">
      <svg
        width="64"
        height="64"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1"
      >
        <path
          d="M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5Z"
        />
        <path d="M12 5L8 21l4-7 4 7-4-16Z" />
      </svg>
      <p>暂无车辆信息</p>
      <button @click="showAddModal = true" class="add-button">
        添加第一辆车
      </button>
    </div>

    <!-- 添加/编辑车辆模态框 -->
    <div
      v-if="showAddModal || showEditModal"
      class="modal-overlay"
      @click.self="closeModals"
    >
      <div class="modal glass-effect">
        <div class="modal-header">
          <h3>{{ showAddModal ? "添加车辆" : "编辑车辆" }}</h3>
          <button @click="closeModals" class="close-button">
            <svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <form @submit.prevent="handleSubmit" class="vehicle-form">
          <div class="form-group">
            <label for="name">车辆名称 *</label>
            <input
              id="name"
              v-model="formData.name"
              type="text"
              required
              placeholder="例如：我的私家车"
              :class="{ error: errors.name }"
            />
            <span v-if="errors.name" class="error-message">{{
              errors.name
            }}</span>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="brand">品牌 *</label>
              <input
                id="brand"
                v-model="formData.brand"
                type="text"
                required
                placeholder="例如：丰田"
                :class="{ error: errors.brand }"
              />
              <span v-if="errors.brand" class="error-message">{{
                errors.brand
              }}</span>
            </div>

            <div class="form-group">
              <label for="model">型号 *</label>
              <input
                id="model"
                v-model="formData.model"
                type="text"
                required
                placeholder="例如：卡罗拉"
                :class="{ error: errors.model }"
              />
              <span v-if="errors.model" class="error-message">{{
                errors.model
              }}</span>
            </div>
          </div>

          <div class="form-group">
            <label for="license_plate">车牌号 *</label>
            <input
              id="license_plate"
              v-model="formData.license_plate"
              type="text"
              required
              placeholder="例如：京A12345"
              :class="{ error: errors.license_plate }"
            />
            <span v-if="errors.license_plate" class="error-message">{{
              errors.license_plate
            }}</span>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="year">年份</label>
              <input
                id="year"
                v-model="formData.year"
                type="number"
                min="1900"
                max="2100"
                placeholder="例如：2020"
              />
            </div>

            <div class="form-group">
              <label for="is_active">状态</label>
              <select id="is_active" v-model="formData.is_active">
                <option :value="true">使用中</option>
                <option :value="false">已停用</option>
              </select>
            </div>
          </div>

          <div class="form-group">
            <label for="notes">备注</label>
            <textarea
              id="notes"
              v-model="formData.notes"
              rows="3"
              placeholder="请输入备注信息（可选）"
            ></textarea>
          </div>

          <div class="form-actions">
            <button type="button" @click="closeModals" class="cancel-button">
              取消
            </button>
            <button type="submit" class="submit-button" :disabled="loading">
              {{ loading ? "保存中..." : showAddModal ? "添加" : "保存" }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div
      v-if="showDeleteModal"
      class="modal-overlay"
      @click.self="showDeleteModal = false"
    >
      <div class="modal glass-effect delete-modal">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button @click="showDeleteModal = false" class="close-button">
            <svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <path d="M18 6L6 18M6 6l12 12" />
            </svg>
          </button>
        </div>

        <div class="delete-content">
          <svg
            width="48"
            height="48"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1"
          >
            <path
              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
            />
          </svg>
          <p>确定要删除车辆 "{{ vehicleToDelete?.name }}" 吗？</p>
          <p class="delete-warning">
            此操作不可撤销，相关的油耗记录也会被删除。
          </p>
        </div>

        <div class="delete-actions">
          <button @click="showDeleteModal = false" class="cancel-button">
            取消
          </button>
          <button
            @click="confirmDelete"
            class="delete-button"
            :disabled="loading"
          >
            {{ loading ? "删除中..." : "确认删除" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useVehicleStore } from "@/stores/vehicle";
import type {
  VehicleResponse,
  VehicleCreate,
  VehicleUpdate,
} from "@/types/vehicle";

// 车辆store
const vehicleStore = useVehicleStore();

// 响应式状态
const vehicles = ref<VehicleResponse[]>([]);
const loading = ref(false);
const showAddModal = ref(false);
const showEditModal = ref(false);
const showDeleteModal = ref(false);
const vehicleToDelete = ref<VehicleResponse | null>(null);
const currentEditingId = ref<number | null>(null);

// 表单数据
const formData = reactive<Partial<VehicleCreate & VehicleUpdate>>({
  name: "",
  brand: "",
  model: "",
  license_plate: "",
  year: undefined,
  is_active: true,
  notes: undefined,
});

// 表单错误
const errors = ref<Record<string, string>>({});

// 清除错误
const clearErrors = () => {
  errors.value = {};
};

// 清除表单
const clearForm = () => {
  currentEditingId.value = null;
  Object.assign(formData, {
    name: "",
    brand: "",
    model: "",
    license_plate: "",
    year: undefined,
    is_active: true,
    notes: undefined,
  });
  clearErrors();
};

// 获取车辆列表
const fetchVehicles = async () => {
  try {
    loading.value = true;
    const response = await vehicleStore.fetchVehicles();
    vehicles.value = response.vehicles;
  } catch (error) {
    console.error("获取车辆列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 编辑车辆
const editVehicle = (vehicle: VehicleResponse) => {
  currentEditingId.value = vehicle.id;
  Object.assign(formData, {
    name: vehicle.name,
    brand: vehicle.brand,
    model: vehicle.model,
    license_plate: vehicle.license_plate,
    year: vehicle.year,
    is_active: vehicle.is_active,
    notes: vehicle.notes,
  });
  showEditModal.value = true;
};

// 删除车辆
const deleteVehicle = (vehicle: VehicleResponse) => {
  vehicleToDelete.value = vehicle;
  showDeleteModal.value = true;
};

// 确认删除
const confirmDelete = async () => {
  if (!vehicleToDelete.value) return;

  try {
    loading.value = true;
    await vehicleStore.deleteVehicle(vehicleToDelete.value.id);
    vehicles.value = vehicles.value.filter(
      (v) => v.id !== vehicleToDelete.value!.id,
    );
    showDeleteModal.value = false;
    vehicleToDelete.value = null;
  } catch (error) {
    console.error("删除车辆失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理表单提交
const handleSubmit = async () => {
  clearErrors();

  // 表单验证
  if (!formData.name) {
    errors.value.name = "请输入车辆名称";
    return;
  }
  if (!formData.brand) {
    errors.value.brand = "请输入车辆品牌";
    return;
  }
  if (!formData.model) {
    errors.value.model = "请输入车辆型号";
    return;
  }
  if (!formData.license_plate) {
    errors.value.license_plate = "请输入车牌号";
    return;
  }

  try {
    loading.value = true;

    if (showAddModal.value) {
      // 创建车辆
      const newVehicle = await vehicleStore.createVehicle(
        formData as VehicleCreate,
      );
      vehicles.value.push(newVehicle);
    } else {
      // 更新车辆
      const updatedVehicle = await vehicleStore.updateVehicle(
        currentEditingId.value!,
        formData as VehicleUpdate,
      );
      const index = vehicles.value.findIndex(
        (v) => v.id === currentEditingId.value,
      );
      if (index !== -1) {
        vehicles.value[index] = updatedVehicle;
      }
    }

    closeModals();
  } catch (error) {
    console.error("保存车辆失败:", error);
  } finally {
    loading.value = false;
  }
};

// 关闭模态框
const closeModals = () => {
  showAddModal.value = false;
  showEditModal.value = false;
  clearForm();
};

// 格式化日期
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString("zh-CN");
};

// 组件挂载时获取数据
onMounted(() => {
  fetchVehicles();
});
</script>

<style scoped lang="scss">
@use "@/styles/mixins" as *;

.vehicle-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.vehicles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.vehicle-card {
  @include glass-morphism;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    @include hover-lift;
  }

  &.inactive {
    opacity: 0.6;
  }
}

.vehicle-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.vehicle-info {
  flex: 1;
}

.vehicle-name {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.vehicle-model {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--text-secondary);
}

.vehicle-badges {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.license-plate {
  background: var(--theme-primary);
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.year-badge {
  background: var(--bg-secondary);
  color: var(--text-secondary);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;

  &.active {
    background: var(--theme-success);
    color: white;
  }

  &.inactive {
    background: var(--theme-warning);
    color: white;
  }
}

.vehicle-actions {
  display: flex;
  gap: 8px;
}

.action-button {
  @include macos-button;
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;

  &.edit {
    background: var(--theme-primary);
    color: white;

    &:hover {
      background: color-mix(in srgb, var(--theme-primary) 80%, black);
    }
  }

  &.delete {
    background: var(--theme-error);
    color: white;

    &:hover {
      background: color-mix(in srgb, var(--theme-error) 80%, black);
    }
  }
}

.vehicle-details {
  border-top: 1px solid var(--border-primary);
  padding-top: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;

  &:last-child {
    margin-bottom: 0;
  }
}

.detail-label {
  font-size: 12px;
  color: var(--text-secondary);
  min-width: 80px;
  margin-right: 8px;
}

.detail-value {
  font-size: 14px;
  color: var(--text-primary);
}

.add-vehicle-card {
  border: 2px dashed var(--border-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    border-color: var(--theme-primary);
    background: var(--bg-secondary);
  }
}

.add-vehicle-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: var(--text-secondary);
}

.add-vehicle-text {
  font-size: 16px;
  font-weight: 500;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);

  svg {
    margin-bottom: 16px;
    opacity: 0.5;
  }

  p {
    margin-bottom: 20px;
    font-size: 16px;
  }
}

.add-button {
  @include macos-button;
  background: var(--theme-primary);
  color: white;
  padding: 12px 24px;

  &:hover {
    background: color-mix(in srgb, var(--theme-primary) 80%, black);
  }
}

// 模态框样式
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: var(--bg-surface);
  border-radius: 16px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid var(--border-primary);

  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
  }
}

.close-button {
  @include macos-button;
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: transparent;
  color: var(--text-secondary);

  &:hover {
    background: var(--bg-secondary);
  }
}

.vehicle-form {
  padding: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-group {
  margin-bottom: 16px;

  label {
    display: block;
    margin-bottom: 6px;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
  }

  input,
  textarea,
  select {
    @include macos-input;
    width: 100%;
  }

  textarea {
    resize: vertical;
    min-height: 80px;
  }

  &.full-width {
    grid-column: 1 / -1;
  }
}

.error-message {
  display: block;
  margin-top: 4px;
  font-size: 12px;
  color: var(--theme-error);
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.cancel-button {
  @include macos-button;
  background: transparent;
  color: var(--text-secondary);
  border: 1px solid var(--border-primary);

  &:hover {
    background: var(--bg-secondary);
  }
}

.submit-button {
  @include macos-button;
  background: var(--theme-primary);
  color: white;

  &:hover {
    background: color-mix(in srgb, var(--theme-primary) 80%, black);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

// 删除确认对话框
.delete-modal {
  max-width: 400px;
}

.delete-content {
  text-align: center;
  padding: 20px;

  svg {
    margin-bottom: 16px;
    color: var(--theme-warning);
  }

  p {
    margin: 0 0 8px 0;
    font-size: 16px;
    color: var(--text-primary);
  }

  .delete-warning {
    font-size: 14px;
    color: var(--text-secondary);
  }
}

.delete-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 20px 20px;
}

.delete-button {
  @include macos-button;
  background: var(--theme-error);
  color: white;

  &:hover {
    background: color-mix(in srgb, var(--theme-error) 80%, black);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

@include mobile {
  .vehicles-grid {
    grid-template-columns: 1fr;
  }

  .form-row {
    grid-template-columns: 1fr;
  }

  .vehicle-header {
    flex-direction: column;
    gap: 12px;
  }

  .vehicle-actions {
    align-self: flex-end;
  }
}
</style>
